package com.example.userservice.Controller;

import com.example.common.utils.CacheClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/Redis")
@Slf4j
public class RedisController {

    @Autowired
    private CacheClient cacheClient;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/test-redis")
    public String testRedis() {
        try {
            log.info("开始测试Redis连接...");

            // 测试基本连接
            String testKey = "test:connection";
            stringRedisTemplate.opsForValue().set(testKey, "test", 10, TimeUnit.SECONDS);
            String value = stringRedisTemplate.opsForValue().get(testKey);
            log.info("基本连接测试: {}", "test".equals(value) ? "成功" : "失败");

            // 测试CacheClient
            String cacheKey = "test:cache";
            cacheClient.set(cacheKey, "cache_test", 10, TimeUnit.SECONDS);
            String cacheValue = cacheClient.get(cacheKey);
            log.info("CacheClient测试: {}", "cache_test".equals(cacheValue) ? "成功" : "失败");

            // 测试Redis配置
            log.info("Redis配置信息:");
            log.info("Host: {}", stringRedisTemplate.getConnectionFactory().getConnection().getClientName());

            return "Redis连接测试成功";
        } catch (Exception e) {
            log.error("Redis连接测试失败: {}", e.getMessage(), e);
            return "Redis连接测试失败: " + e.getMessage();
        }
    }
}
